package com.demo.security.cloud.controller;

import com.alibaba.fastjson.JSON;
import com.demo.security.cloud.entity.dto.UserDto;
import com.demo.security.cloud.service.impl.SpringDataUserDetailsService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpSession;

@RestController
public class IndexController {

	private static final Logger logger = LoggerFactory.getLogger(IndexController.class);

	@GetMapping(value = "/hello", produces = "text/plain;charset=utf-8")
	public String hello() {
		return "hello jwt uaa";
	}

	@GetMapping(value = "/anymouse", produces = "text/plain;charset=utf-8")
	public String anymouse(HttpSession session){
		String fullName;
		Object object = session.getAttribute(UserDto.SESSION_KEY);
		if (object == null){
			fullName = "anymouse";
		}else {
			fullName = ((UserDto)object).getUserName();
		}

		return fullName;
	}

	@GetMapping(value = "/r/r1", produces = "text/plain;charset=utf-8")
	@PreAuthorize("hasAuthority('p1')")
	public String r1(){
		return "resource: r1";
	}

	@GetMapping(value = "/r/r2", produces = "text/plain;charset=utf-8")
	@PreAuthorize("hasAuthority('p2')")
	public String r2(){
		return "resource: r2";
	}

	@RequestMapping(value = "/loginSuccess", produces = "text/plain;charset=utf-8")
	public ModelAndView index2(ModelAndView mv) {
		logger.info("loginSuccess");
		mv.setViewName("/index2");
		mv.addObject("user", getUserName());
		return mv;
	}

	private String getUserName(){
		Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
		Object credentials = authentication.getCredentials();
		Object principal = authentication.getPrincipal();
		Object details = authentication.getDetails();
		String name = authentication.getName();
		System.out.println(JSON.toJSONString(principal));
		System.out.println(JSON.toJSONString(credentials));
		System.out.println(JSON.toJSONString(details));

		if (principal == null){
			return "匿名";
		}

		if (principal instanceof UserDetails){
			return ((UserDetails)principal).getUsername();
		}

		return name;
	}
}
 
